// 北京国庆出游规划助手 - JavaScript应用逻辑

class BeijingTravelApp {
    constructor() {
        this.apiBase = 'http://localhost:8080';
        this.attractions = [];
        this.currentPlans = [];
        
        this.init();
    }

    init() {
        this.loadAttractions();
        this.bindEvents();
        this.setupSmoothScrolling();
    }

    // 绑定事件监听器
    bindEvents() {
        const form = document.getElementById('planning-form');
        if (form) {
            form.addEventListener('submit', (e) => this.handlePlanSubmit(e));
        }

        // 导航链接平滑滚动
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', (e) => {
                e.preventDefault();
                const target = document.querySelector(anchor.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            });
        });
    }

    // 设置平滑滚动
    setupSmoothScrolling() {
        // 添加滚动动画效果
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // 观察所有卡片元素
        document.querySelectorAll('.card, .timeline-item').forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(el);
        });
    }

    // 加载景点数据
    async loadAttractions() {
        try {
            // 使用本地数据（模拟API）
            this.attractions = [
                {
                    id: 1,
                    name: "故宫博物院",
                    description: "明清两代的皇家宫殿，世界文化遗产，拥有600年历史",
                    location: "东城区景山前街4号",
                    ticket_price: 60,
                    recommended_duration: 4,
                    best_time: "上午8:00-12:00",
                    crowd_level: "高",
                    transport: ["地铁1号线天安门东站", "地铁8号线故宫站"],
                    image: "https://via.placeholder.com/300x200/8B4513/FFFFFF?text=故宫"
                },
                {
                    id: 2,
                    name: "天安门广场",
                    description: "世界最大的城市广场之一，观看升旗仪式",
                    location: "东城区东长安街",
                    ticket_price: 0,
                    recommended_duration: 2,
                    best_time: "升旗仪式时间",
                    crowd_level: "高",
                    transport: ["地铁1号线天安门东站", "地铁2号线前门站"],
                    image: "https://via.placeholder.com/300x200/DC143C/FFFFFF?text=天安门"
                },
                {
                    id: 3,
                    name: "颐和园",
                    description: "清朝皇家园林，世界文化遗产，昆明湖和万寿山",
                    location: "海淀区新建宫门路19号",
                    ticket_price: 30,
                    recommended_duration: 4,
                    best_time: "上午9:00-下午3:00",
                    crowd_level: "中",
                    transport: ["地铁4号线北宫门站", "地铁16号线颐和园站"],
                    image: "https://via.placeholder.com/300x200/4169E1/FFFFFF?text=颐和园"
                },
                {
                    id: 4,
                    name: "长城-八达岭段",
                    description: "世界文化遗产，中国古代军事防御工程",
                    location: "延庆区八达岭特区",
                    ticket_price: 40,
                    recommended_duration: 4,
                    best_time: "上午8:00-下午2:00",
                    crowd_level: "高",
                    transport: ["京张高铁八达岭长城站", "公交877路"],
                    image: "https://via.placeholder.com/300x200/8B7355/FFFFFF?text=长城"
                },
                {
                    id: 5,
                    name: "天坛公园",
                    description: "明清皇帝祭天场所，世界文化遗产",
                    location: "东城区天坛路甲1号",
                    ticket_price: 15,
                    recommended_duration: 3,
                    best_time: "上午8:00-11:00",
                    crowd_level: "中",
                    transport: ["地铁5号线天坛东门站", "地铁8号线天桥站"],
                    image: "https://via.placeholder.com/300x200/228B22/FFFFFF?text=天坛"
                },
                {
                    id: 6,
                    name: "圆明园遗址公园",
                    description: "清代大型皇家园林遗址，历史的见证",
                    location: "海淀区清华西路28号",
                    ticket_price: 10,
                    recommended_duration: 3,
                    best_time: "上午9:00-下午4:00",
                    crowd_level: "中",
                    transport: ["地铁4号线圆明园站"],
                    image: "https://via.placeholder.com/300x200/696969/FFFFFF?text=圆明园"
                },
                {
                    id: 7,
                    name: "北海公园",
                    description: "中国现存最古老的皇家园林，白塔和琼岛",
                    location: "西城区文津街1号",
                    ticket_price: 10,
                    recommended_duration: 2,
                    best_time: "上午9:00-下午5:00",
                    crowd_level: "中",
                    transport: ["地铁6号线北海北站", "地铁8号线什刹海站"],
                    image: "https://via.placeholder.com/300x200/4682B4/FFFFFF?text=北海"
                },
                {
                    id: 8,
                    name: "798艺术区",
                    description: "现代艺术文化聚集地，创意工厂",
                    location: "朝阳区酒仙桥路4号",
                    ticket_price: 0,
                    recommended_duration: 3,
                    best_time: "上午10:00-下午6:00",
                    crowd_level: "低",
                    transport: ["地铁14号线将台站", "公交401路"],
                    image: "https://via.placeholder.com/300x200/FF6347/FFFFFF?text=798"
                },
                {
                    id: 9,
                    name: "奥林匹克公园",
                    description: "2008年北京奥运会主场馆，鸟巢和水立方",
                    location: "朝阳区北辰东路15号",
                    ticket_price: 0,
                    recommended_duration: 2,
                    best_time: "全天",
                    crowd_level: "中",
                    transport: ["地铁8号线奥体中心站", "地铁15号线北辰站"],
                    image: "https://via.placeholder.com/300x200/4169E1/FFFFFF?text=奥林匹克"
                },
                {
                    id: 10,
                    name: "南锣鼓巷",
                    description: "老北京胡同文化体验区，传统与现代融合",
                    location: "东城区南锣鼓巷",
                    ticket_price: 0,
                    recommended_duration: 2,
                    best_time: "上午10:00-下午5:00",
                    crowd_level: "高",
                    transport: ["地铁6号线南锣鼓巷站", "地铁8号线什刹海站"],
                    image: "https://via.placeholder.com/300x200/8B4513/FFFFFF?text=南锣鼓巷"
                }
            ];
            
            this.renderAttractions();
        } catch (error) {
            console.error('加载景点数据失败:', error);
            this.showError('加载景点数据失败，请检查网络连接');
        }
    }

    // 渲染景点卡片
    renderAttractions() {
        const container = document.getElementById('attractions-container');
        if (!container) return;

        container.innerHTML = '';
        
        this.attractions.forEach(attraction => {
            const crowdColor = {
                '高': 'danger',
                '中': 'warning',
                '低': 'success'
            };

            const card = `
                <div class="col-md-6 col-lg-4 col-xl-3 mb-4">
                    <div class="card attraction-card h-100">
                        <img src="${attraction.image}" 
                             class="card-img-top" 
                             alt="${attraction.name}"
                             style="height: 150px; object-fit: cover;">
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title text-primary">${attraction.name}</h5>
                            <p class="card-text flex-grow-1" style="font-size: 0.9rem;">
                                ${attraction.description}
                            </p>
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-1">
                                <span class="badge bg-primary">¥${attraction.ticket_price}</span>
                                <span class="badge bg-info">${attraction.recommended_duration}小时</span>
                                <span class="badge bg-${crowdColor[attraction.crowd_level]}">
                                    ${attraction.crowd_level}
                                </span>
                            </div>
                            <small class="text-muted mt-2">
                                <i class="fas fa-map-marker-alt"></i> ${attraction.location}
                            </small>
                        </div>
                    </div>
                </div>
            `;
            container.innerHTML += card;
        });
    }

    // 处理路线规划提交
    async handlePlanSubmit(e) {
        e.preventDefault();
        
        const startLocation = document.getElementById('start-location').value.trim();
        const days = parseInt(document.getElementById('days').value);
        const preference = document.getElementById('preference').value;

        if (!startLocation || !days || !preference) {
            this.showError('请填写完整信息');
            return;
        }

        this.showLoading(true);
        
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000));
            const plans = this.generateMockPlans(startLocation, days, preference);
            this.displayPlans(plans);
        } catch (error) {
            console.error('生成路线失败:', error);
            this.showError('生成路线失败，请稍后重试');
        } finally {
            this.showLoading(false);
        }
    }

    // 显示/隐藏加载状态
    showLoading(show) {
        const button = document.querySelector('#planning-form button[type="submit"]');
        if (button) {
            if (show) {
                button.innerHTML = '<span class="loading"></span> 生成中...';
                button.disabled = true;
            } else {
                button.innerHTML = '<i class="fas fa-magic"></i> 生成路线规划';
                button.disabled = false;
            }
        }
    }

    // 生成模拟路线方案
    generateMockPlans(startLocation, days, preference) {
        const plans = [];
        
        // 根据偏好筛选景点
        let filteredAttractions = [...this.attractions];
        if (preference !== '全部') {
            const preferenceMap = {
                '文化古迹': ['故宫', '天坛', '颐和园', '圆明园'],
                '现代都市': ['798', '奥林匹克', '南锣鼓巷'],
                '自然风光': ['北海', '颐和园', '圆明园']
            };
            
            const keywords = preferenceMap[preference] || [];
            filteredAttractions = this.attractions.filter(a => 
                keywords.some(keyword => a.name.includes(keyword))
            );
            
            if (filteredAttractions.length === 0) {
                filteredAttractions = this.attractions;
            }
        }

        // 生成3种不同的方案
        for (let planId = 1; planId <= 3; planId++) {
            const shuffled = [...filteredAttractions].sort(() => Math.random() - 0.5);
            const dailyHours = 8;
            const totalHours = days * dailyHours;
            
            let currentHours = 0;
            let totalCost = 0;
            const selectedAttractions = [];
            
            // 智能分配景点
            for (const attraction of shuffled) {
                if (currentHours + attraction.recommended_duration <= totalHours * 0.9) {
                    selectedAttractions.push({
                        ...attraction,
                        day: Math.floor(currentHours / dailyHours) + 1,
                        timeSlot: this.getTimeSlot(currentHours % dailyHours)
                    });
                    currentHours += attraction.recommended_duration;
                    totalCost += attraction.ticket_price;
                    
                    // 添加交通时间
                    currentHours += 0.5;
                }
                
                if (currentHours >= totalHours * 0.85) break;
            }

            // 计算交通建议
            let transportSuggestion = '建议使用地铁和公交组合';
            if (startLocation.includes('机场')) {
                transportSuggestion = '建议乘坐机场快轨+地铁组合';
            } else if (startLocation.includes('火车站')) {
                transportSuggestion = '建议直接乘坐地铁，避开高峰期';
            }

            plans.push({
                plan_id: planId,
                total_duration: Math.round(currentHours),
                total_cost: totalCost,
                transport_suggestion: transportSuggestion,
                attractions: selectedAttractions,
                days: days
            });
        }

        return plans;
    }

    // 获取时间段
    getTimeSlot(hour) {
        if (hour < 3) return '上午9:00-12:00';
        if (hour < 6) return '下午1:00-4:00';
        return '下午4:00-6:00';
    }

    // 显示路线方案
    displayPlans(plans) {
        const container = document.getElementById('plans-container');
        const resultsSection = document.getElementById('results');
        
        if (!container || !resultsSection) return;

        container.innerHTML = '';
        
        plans.forEach(plan => {
            // 按天分组景点
            const attractionsByDay = {};
            plan.attractions.forEach(attraction => {
                if (!attractionsByDay[attraction.day]) {
                    attractionsByDay[attraction.day] = [];
                }
                attractionsByDay[attraction.day].push(attraction);
            });

            const planCard = `
                <div class="card mb-4 border-0 shadow-lg">
                    <div class="card-header bg-gradient-primary text-white" 
                         style="background: linear-gradient(135deg, #667eea, #764ba2);">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-route"></i> 方案 ${plan.plan_id}
                            </h5>
                            <div>
                                <span class="badge bg-light text-dark me-2">
                                    <i class="fas fa-coins"></i> ¥${plan.total_cost}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-clock"></i> ${plan.total_duration}小时
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fas fa-lightbulb"></i>
                            <strong>交通建议：</strong> ${plan.transport_suggestion}
                        </div>
                        
                        ${Object.entries(attractionsByDay).map(([day, attractions]) => `
                            <div class="mb-4">
                                <h6 class="text-primary mb-3">
                                    <i class="fas fa-calendar-day"></i> 第${day}天
                                </h6>
                                <div class="timeline">
                                    ${attractions.map((attraction, index) => `
                                        <div class="timeline-item">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-shrink-0">
                                                    <span class="badge bg-primary rounded-circle">
                                                        ${index + 1}
                                                    </span>
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <h6 class="mb-1">${attraction.name}</h6>
                                                    <p class="text-muted mb-1" style="font-size: 0.9rem;">
                                                        ${attraction.description}
                                                    </p>
                                                    <div class="d-flex gap-3 flex-wrap">
                                                        <small class="text-muted">
                                                            <i class="fas fa-clock"></i> ${attraction.timeSlot}
                                                        </small>
                                                        <small class="text-muted">
                                                            <i class="fas fa-hourglass-half"></i> ${attraction.recommended_duration}小时
                                                        </small>
                                                        <small class="text-muted">
                                                            <i class="fas fa-ticket-alt"></i> ¥${attraction.ticket_price}
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
            container.innerHTML += planCard;
        });

        resultsSection.style.display = 'block';
        setTimeout(() => {
            resultsSection.scrollIntoView({ behavior: 'smooth' });
        }, 100);
    }

    // 显示错误信息
    showError(message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 400px;';
        alertDiv.innerHTML = `
            <i class="fas fa-exclamation-triangle"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 5000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new BeijingTravelApp();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = BeijingTravelApp;
}
